package com.android.volley.caches;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

/**
 * @author ChameleonChen
 */
public class LruImageCache implements ImageCache {

    private static LruCache<String, Bitmap> memoryCache;
    private static LruImageCache lruImageCache;

    private LruImageCache() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;
        memoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
    }

    public static LruImageCache getInstance() {
        if (lruImageCache == null)
            lruImageCache = new LruImageCache();

        return lruImageCache;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return memoryCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (memoryCache.get(url) == null) {
            memoryCache.put(url, bitmap);
        }
    }
}
